const express = require("express")
const { ApiResponse, tokenMiddleware } = require('./api_response')
const fs = require("fs")
const router = express.Router()

// 文件上传
router.post("/upload", tokenMiddleware, async (req, res) => {
    let apiRes = new ApiResponse(res);
    //检测是否有文件
    if (!req.files) {
        apiRes.validateFailed('上传文件不能为空')
        return
    }

    //保存文件
    let files = req.files;
    let ret_files = [];
    for (let file of files) {
        //获取名字后缀
        let file_ext = file.originalname.substring(file.originalname.lastIndexOf(".") + 1);
        //使用时间戳作为文件名字
        let file_name = new Date().getTime() + "." + file_ext;
        // 移动文件并且修改文件名字
        fs.renameSync(
            process.cwd() + "/public/upload/temp/" + file.filename,
            process.cwd() + "/public/upload/temp/" + file_name,
        );

        let fileUrl = `http://${global.localIP}:${global.port}/upload/temp/` + file_name;
        ret_files.push(fileUrl);
    }

    apiRes.success(ret_files);
})

//下载文件
router.get("/download", tokenMiddleware, (req, res) => {
    let file_name = req.query.file_name;
    let filePath = process.cwd() + "/public/" + file_name;
    let apiRes = new ApiResponse(res);
    fs.access(filePath, fs.constants.F_OK, (err) => {
        if (err) {
            //console.error(`文件不存在: ${filePath}`);
            apiRes.validateFailed(`文件不存在: ${filePath}`)
        } else {
            //console.log(`文件存在: ${filePath}`);
            apiRes.download(filePath);
        }
    });
})

module.exports = router